package com.effectiv.crm.controller;

import javax.inject.Inject;
import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.effectiv.crm.domain.Account;

import com.effectiv.crm.service.api.AccountService;


@Slf4j
@Controller
@RequestMapping("/account")
public class AccountController {
	
	@Inject
	private AccountService service;

	@RequestMapping("/list")
	public String list(Model model) {
		model.addAttribute(service.findAll());
		return "listaccounts";
	}

	
	
	@RequestMapping(value={"/edit","/new"})
	public String editLead(Model model,@RequestParam("id") String id
			) {
		
		if(StringUtils.isEmpty(id)) {
		
			model.addAttribute(BeanUtils.instantiate(Account.class));
		}
		else{
			Account account = service.findOne(id);
			
			//handle missing lead
			if(account == null){
				account = BeanUtils.instantiate(Account.class);
				
			}
			
			
			log.info("account ==== {}", account);
			
			model.addAttribute(account);
		}
		
		return "newaccount";
	}
	
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(@Valid Account account,
			BindingResult result, Model m) {
		
		log.info("Contact submitted for saving - {}", account);
		
		if (result.hasErrors()) {
			//model.addAttribute(BeanUtils.instantiate(Lead.class));
			return "newaccount";
		}
		else{
			service.save(account);
			m.addAttribute("message",
					"Account saved successfully.");
		}
  
		
		return "newaccount";
	}
	

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String submitForm(@Valid  Account account,
			BindingResult result, Model m) {
		
		log.info("account submitted for saving - {}", account);
		
		if (result.hasErrors()) {
			//model.addAttribute(BeanUtils.instantiate(Lead.class));
			return "newlead";
		}
		else{
			service.save(account);
			m.addAttribute("message",
					"account saved successfully.");
		}

		
		return "newaccount";
	}
}
